package ru.tomsk.autovokzal.activity.adapter;

import java.util.List;

import ru.tomsk.autovokzal.R;
import ru.tomsk.autovokzal.tools.MainMenuItem;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MainMenuAdapter extends ArrayAdapter<MainMenuItem> {

	public static class ViewHolder {
		public ImageView image_id;
		public TextView text;
		public Intent intent;
		public Context cntx;
	}

	private static final int MAIN_MENU_ITEM = R.layout.main_menu_item;
	private List<MainMenuItem> itemsArray;
	private Context context;
	private MainMenuItem item;
	private ViewHolder holder;

	public MainMenuAdapter(Context context, List<MainMenuItem> objects) {
		super(context, MAIN_MENU_ITEM, objects);
		this.context = context;
		this.itemsArray = objects;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.widget.ArrayAdapter#getView(int, android.view.View,
	 * android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		item = itemsArray.get(position);
		if (convertView == null) {
			holder = new ViewHolder();
			LayoutInflater inflate = LayoutInflater.from(context);
			convertView = inflate.inflate(MAIN_MENU_ITEM, null);
			holder.image_id = (ImageView) convertView
					.findViewById(R.id.main_menu_element_image);
			holder.text = (TextView) convertView
					.findViewById(R.id.main_menu_element_text);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.image_id.setBackgroundDrawable(context.getResources()
				.getDrawable(item.getMenu_item_image_id()));
		holder.intent = item.getNext_activity();
		holder.cntx = item.getContext();
		holder.text.setText(item.getMenu_item_text());
		convertView.setTag(holder);
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ViewHolder tmp_holder = (ViewHolder) v.getTag();
				if (tmp_holder.cntx != null)
					if (tmp_holder.intent != null)
					{
						tmp_holder.cntx.startActivity(tmp_holder.intent);
					}

			}
		});
		return convertView;
	}

}
